import { useUserStore } from '@/store';
import type { MenuItem } from '@/store/modules/user/types';

export const getMenuObjByList = () => {
  const { menus, setInfo } = useUserStore();

  const obj: Record<string, MenuItem> = {};

  menus.forEach((t) => {
    obj[t.name] = t;
  });

  setInfo({
    menusObj: obj,
  });
};

// 列表转树状结构
export const buildTree = (list: MenuItem[], parentId: number) => {
  const tree: any[] = [];
  for (let i = 0; i < list.length; i += 1) {
    if (list[i].parentId === parentId) {
      const node = {
        ...list[i],
        children: buildTree(list, list[i].id),
      };
      tree.push(node);
    }
  }
  return tree;
};

export const getMenu = () => {
  const { menus } = useUserStore();
  if (menus.length) {
    return buildTree(menus, 0);
  }

  return [];
};
